<template>
  <el-dialog v-model="showCopyDialog" title="批量复制栏目" width="680px" @open="handleOpen" :before-close="handleClose">
    <div class="copy-header">
      <span class="copy-count">当前复制数量: {{ form.copies.length }}</span>
      <el-button type="primary" link @click="addCopyItem">
        <el-icon>
          <Plus />
        </el-icon>
        添加复制项
      </el-button>
    </div>

    <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
      <el-scrollbar max-height="300px" style="width: 100%;">
        <div v-for="(item, index) in form.copies" :key="index" class="copy-item">
          <div class="copy-item-header">
            <div class="copy-item-title">
            <span class="copy-index">{{ index + 1 }}</span>
            <span>复制项</span>
          </div>
          <el-button v-if="form.copies.length > 1" type="danger" link @click="removeCopyItem(index)">
            <el-icon>
              <Delete />
            </el-icon>
            删除
          </el-button>
        </div>
        <div class="copy-item-content">
          <el-form-item :label="'栏目名称'" :prop="'copies.' + index + '.name'" :rules="formRules.name">
            <el-input v-model="item.name" placeholder="请输入栏目名称" @change="() => handleBlurName(index)" />
          </el-form-item>
          <el-form-item :label="'栏目uri'" :prop="'copies.' + index + '.uri'" :rules="formRules.uri">
            <el-input v-model="item.uri" placeholder="输入栏目名称后点击回车自动生成" />
          </el-form-item>
          </div>
        </div>
      </el-scrollbar>

      <el-divider content-position="left">子栏目选择</el-divider>

      <el-form-item>
        <div class="tree-header">
          <el-checkbox v-model="isAllSelected" @change="handleSelectAll">全选</el-checkbox>
        </div>
        <el-scrollbar ref="treeScrollbar" max-height="300px" style="width: 100%;">
          <el-tree ref="treeRef" :data="children" show-checkbox default-expand-all node-key="id" highlight-current
            :props="treeProps" @check="handleTreeCheck" />
        </el-scrollbar>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, inject, nextTick } from 'vue'
import { useStore } from 'vuex'
import { pinyin } from 'pinyin-pro'
import { copyCategoryBatch } from '@/api/category'
import { ElMessage } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'

const emits = defineEmits(['success'])
const store = useStore()
const { showCopyDialog, sourceId, sourceUri } = inject('copyData')

const uriValidate = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请输入栏目路径'))
    return
  }
  // 允许以/开头,后面只能包含字母数字下划线
  const regex = /^\/[a-zA-Z0-9_]+$/
  if (!regex.test(value)) {
    callback(new Error('栏目路径只能以/开头,后面只能包含字母、数字和下划线'))
    return
  }
  callback()
}

const formRules = {
  name: [{ required: true, message: '请输入栏目名称', trigger: 'blur' }],
  uri: [{ required: true, validator: uriValidate, trigger: 'change' }]
}

const form = reactive({
  copies: [{
    sourceId: null,
    name: '',
    uri: '',
    children: []
  }]
})

const formRef = ref(null)
const treeScrollbar = ref(null)

// 添加复制项
const addCopyItem = () => {
  form.copies.push({
    sourceId: sourceId.value,
    name: '',
    uri: '',
    children: []
  })
  // 等待DOM更新后滚动到新添加的项
  nextTick(() => {
    const newItem = document.querySelector(`.copy-item:nth-last-child(1)`)
    if (newItem) {
      newItem.scrollIntoView({ behavior: 'smooth', block: 'center' })
    }
  })
}

// 删除复制项
const removeCopyItem = (index) => {
  form.copies.splice(index, 1)
}

// 输入栏目名称后自动生成uri
const handleBlurName = (index) => {
  const item = form.copies[index]
  // 获取最后一个下划线之前的内容作为前缀
  const lastUnderscoreIndex = sourceUri.value.lastIndexOf('_')
  const firstName = lastUnderscoreIndex === -1 ? '/' : sourceUri.value.substring(0, lastUnderscoreIndex + 1)
  const secondName = getSecondName(item, firstName)
  item.uri = firstName + secondName
}

const getSecondName = (data, firstName) => {
  // 如果名称是空的，返回空字符串
  if (!data.name) return ''
  
  // 首先移除所有特殊字符，并将空格替换为下划线
  const cleanName = data.name.replace(/[^\p{L}\p{N}\s_]/gu, '').replace(/\s+/g, '_')
  
  // 判断是否包含中文字符
  const hasChinese = /[\u4e00-\u9fa5]/.test(cleanName)
  
  if (hasChinese) {
    // 如果是中文，使用拼音逻辑
    return pinyin(cleanName, {pattern: 'first', toneType: 'none', type: 'array'}).join('')
  } else {
    // 如果是英文，转为小写
    const lowerName = cleanName.toLowerCase()
    
    // 如果长度超过50，则取每个单词的首字母
    if (firstName.length + lowerName.length > 20) {
      return lowerName
        .split('_')
        .map(word => word.charAt(0))
        .join('')
    }
    
    // 否则直接返回处理后的名称
    return lowerName
  }
}

// 打开
const children = ref([])
const treeRef = ref(null)
const treeProps = ref({
  label: 'name',
  children: 'children'
})

const handleOpen = () => {
  form.copies[0].sourceId = sourceId.value
  // 递归查找源栏目
  const findSourceCategory = (tree) => {
    const found = tree.find(item => item.id === sourceId.value)
    if (found) return found

    for (const node of tree) {
      if (node.children && node.children.length) {
        const result = findSourceCategory(node.children)
        if (result) return result
      }
    }
    return null
  }

  const sourceCategory = findSourceCategory(store.state.category.siteCategoryTree)
  children.value = sourceCategory?.children || []
}

// 关闭
const handleClose = () => {
  formRef.value?.resetFields()
  form.copies = [{
    sourceId: null,
    name: '',
    uri: '',
    children: []
  }]
  showCopyDialog.value = false
}

// 提交
const loading = ref(false)
const handleSubmit = () => {
  const selectedChildren = treeRef.value.getCheckedNodes(false, true)
    .filter(item => item.id !== sourceId.value)
    .map(item => item.id)

  // 为所有复制项设置相同的 children
  form.copies.forEach(item => {
    item.sourceId = sourceId.value
    item.children = selectedChildren
  })
  formRef.value.validate((valid) => {
    if (valid) {
      try {
        loading.value = true
        copyCategoryBatch(form.copies).then(async res => {
          if (res.code === 20000) {
            ElMessage.success('批量复制成功')
            store.commit('category/CLEAR_CHECKED_CATEGORIES')
            await store.dispatch('category/updateCategory')
            handleClose()
            nextTick(() => {
              emits('success')
            })
          } else {
            ElMessage.error(res.msg)
          }
        })
      } finally {
        loading.value = false
      }
    }
  })
}

const isAllSelected = ref(false)
// 全选/取消全选子栏目
const handleSelectAll = (val) => {
  const allKeys = Object.values(treeRef.value.store.nodesMap).map(node => node.data.id)
  treeRef.value.setCheckedKeys(val ? allKeys : [])
}

// 监听树节点选中状态变化
const handleTreeCheck = () => {
  const allKeys = Object.values(treeRef.value.store.nodesMap).map(node => node.data.id)
  const checkedKeys = treeRef.value.getCheckedKeys()
  isAllSelected.value = allKeys.length > 0 && allKeys.length === checkedKeys.length
}
</script>

<style scoped>
.copy-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.copy-count {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.copy-item {
  background-color: var(--el-fill-color-light);
  border-radius: 8px;
  margin-bottom: 16px;
  transition: all 0.3s ease;
}

.copy-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.copy-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background-color: var(--el-fill-color);
  border-radius: 8px 8px 0 0;
}

.copy-item-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
}

.copy-index {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  background-color: var(--el-color-primary);
  color: white;
  border-radius: 50%;
  font-size: 14px;
}

.copy-item-content {
  padding: 16px;
}

:deep(.el-form-item:last-child) {
  margin-bottom: 0;
}

.el-divider {
  margin: 24px 0;
}

:deep(.el-scrollbar__wrap) {
  padding-right: 16px;
}

:deep(.el-button) {
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.tree-header {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;
}
</style>
